/*
 * @Author: JYJ 
 * @Date: 2020-07-11 22:09:54 
 * @Desc: 基于二进制的消息
 */
namespace gf {
    export class ByteArrayMsg implements gf.BaseMsg {
        private _msgBuffer: egret.ByteArray;
        public constructor() {
            this._msgBuffer = new egret.ByteArray();
        }

        /**
         * 接收消息处理
         * @param msg
         */
        public receive(socket: egret.WebSocket): void {
            socket.readBytes(this._msgBuffer);
            do {
                var obj: any = this.decode(this._msgBuffer);
                if (null != obj) {
                    Game.NetworkEngine.netEvent.dispatch(NetEvent.ON_MESSAGE, obj);
                    //解析成功，分发消息
                    console.log(obj.PWD);
                } else {
                    break;
                }
            } while (this._msgBuffer.bytesAvailable > 0)
            if (this._msgBuffer.bytesAvailable == 0) {
                this._msgBuffer.clear();
            }
        }

        /**
         * 发送消息处理
         * @param msg
         */
        public send(socket: egret.WebSocket, msgID: number, msg: any): void {
            var obj: any = this.encode(msgID, msg);
            if (obj) {
                obj.position = 0;
                socket.writeBytes(obj, 0, obj.bytesAvailable);
            }
        }

        /**
         * 消息解析
         * @param msg
         */
        public decode(msg: any): any {
            Log.log("decode需要子类重写，根据项目的协议结构解析");
            return null;
        }

        /**
         * 消息封装
         * @param msg
         */
        public encode(msgID: number, msg: any): any {
            Log.log("encode需要子类重写，根据项目的协议结构解析");
            return null;
        }
    }
}